package com.core.initialize;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.Attribute;

import com.core.EnginService;
import com.core.NetChannel;
import com.core.ServerAttributeKey;
import com.core.action.MessageAction;
import com.core.interfaces.IHandler;

/**
 * 服务器网络层业务接受handler
 * 由此像业务层派发业务
 * @author King
 *
 */
public class ServerChannelHandler extends SimpleChannelInboundHandler<Message> 
{
	protected EnginService service;
	
	public void setEnginService(EnginService service)
	{
		this.service = service;
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		super.channelActive(ctx);
		service.getChannelManager().addChannel(ctx.channel());
	}
	
	@Override
	protected void channelRead0(ChannelHandlerContext ctx, Message msg)
			throws Exception
	{
		IHandler handler = service.getHandlerManager().getHandler(msg.getModule(), msg.getAction());
		service.getExecutor().pushAction(new MessageAction(handler, msg));
	}
	
	
	@Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (!(evt instanceof IdleStateEvent)) {
            return;
        }
        IdleStateEvent e = (IdleStateEvent) evt;
        //TODO 做一些心跳的事情 ping pong 一次
        if (e.state() == IdleState.READER_IDLE) {
//        	losetConnect(ctx);
            System.out.println("心跳没有收到客户端信息");
        }
    }
	
	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception
	{
		super.channelInactive(ctx);
		losetConnect(ctx);
		
	}
	
	/**
	 * 丢失连接   
	 * 模拟玩家退出游戏消息
	 * @param ctx
	 */
	private void losetConnect(ChannelHandlerContext ctx)
	{
		Message msg = Message.newMessage();
		Attribute<NetChannel> attr = ctx.channel().attr(ServerAttributeKey.netChannel);
		NetChannel channel = attr.get();
		service.getChannelManager().delChannel(ctx.channel());
		if(channel==null||channel.isKick())
		{
			return;
		}
		msg.setChannel(attr.get());
		//2,8代表退出游戏  建 C2SMessageId  类
		msg.setModuleAction(2, 8);
		
		IHandler handler = service.getHandlerManager().getHandler(msg.getModule(), msg.getAction());
		service.getExecutor().pushAction(new MessageAction(handler, msg));
	}
	
}
